from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDishes, collectionDishList, collectionImageList, dbSynPosDining, collectionDiningList
import operator
from app.globals.publicMethod import globalTimeToString
from flask import send_from_directory
import cv2, os
import base64
import numpy as np
from app.settings.base import image_path

def queryAllClass(diningNo, stallNo):
    '''
    查询某档口所有菜品类别
    "classList": [
        {
            "className": "",
            "classSort": 1
        }
    ],
    "dishList": [
        {
            "classNames": ["className1", "className2", ...]
        }
    ]
    '''
    try:       
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = mg_client[dbSynPosDishes][collectionDishList].find_one(cond)
        res_classList = []
        if res is None:
            return res_classList

        dishList = res.get('dishList')
        if dishList is None:
            return res_classList

        if len(dishList) <= 0: # 防止None崩溃
            return res_classList

        # 将dishList下的menuNames[]中的类别名去重存储
        # classNames = ["素菜", "肉菜"]
        classNames = []
        for v in dishList:
            # 该菜品没通过审核
            # if v.get('dishState') != 'pass':
            #     continue
            cn = v.get('classNames')
            if cn is not None:
                for v1 in cn:
                    if v1 not in classNames:
                        classNames.append(v1)

        # dishList档口菜品表中的classList=[{"className": "主食", "classSort": 1},{}]
        classList = res.get('classList')
        if classList is None:
            for class_name in classNames:
                cls = {'className': class_name, 'classSort': 1}
                res_classList.append(cls)

            return res_classList

        for class_name in classNames:
            classSort = 1
            for v in classList:
                if v.get('className') == class_name:
                    classSort = v.get('classSort')
                    break
            if classSort is None:
                classSort = 1

            cls = {'className': class_name, 'classSort': classSort}
            res_classList.append(cls)

        # reverse=False 升序
        res_classList = sorted(res_classList, key=operator.itemgetter('classSort'), reverse=False)
        return res_classList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryDishes(diningNo, stallNo, dishState, meunName):
    '''
    查询档口菜品基础信息
    '''
    try:       
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = mg_client[dbSynPosDishes][collectionDishList].find_one(cond)

        dishList = []
        if res is None:
            return dishList

        diningName, stallName = queryDiningNameStallName(diningNo, stallNo)

        tempList = res.get('dishList')
        if tempList is None or len(tempList)<=0:
            return dishList

        for v in tempList:
            v['diningNo'] = diningNo
            v['diningName'] = diningName
            v['stallNo'] = stallNo
            v['stallName'] = stallName
            v['createTime'] = globalTimeToString(v.get('createTime'))
            v['updateTime'] = globalTimeToString(v.get('updateTime'))
            imageUrl = ''
            imageId = v.get('imageId')
            if imageId is not None and len(imageId) > 10:
                imageUrl = f'/api/dish/v1/query_Img/{imageId}'
            v['imageUrl'] = imageUrl
            dishList.append(v)

        dishList2 = []
        for w in dishList:
            if w.get('dishState') == dishState:
                dishList2.append(w)

        if len(dishList2) >= 0:
            dishList = dishList2

        dishList3 = []
        if '全部' != meunName:
            for x in dishList:
                if meunName in x.get('menuNames'):
                    dishList3.append(x)
            dishList = dishList3
            
        # reverse=False 升序
        dishList = sorted(dishList, key=operator.itemgetter('dishSort'), reverse=False)

        return dishList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryBatchDishes(userType, diningNos, stallNos, dishState, meunName, startPage, pageSize):
    '''
    批量查询档口菜品基础信息
    '''
    totalPages = 0
    totalCount = 0
    dishList = []
    if diningNos is None or stallNos is None:
        return totalPages, totalCount, dishList

    try:
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosDishes][collectionDishList].find()
        if res is None:
            return totalPages, totalCount, dishList

        for u in res:
            if len(diningNos) == 0 and len(stallNos) == 0:
                if userType == 'all':
                    diningNo = u.get('diningNo')
                    stallNo = u.get('stallNo')
                    diningName, stallName = queryDiningNameStallName(diningNo, stallNo)
                    tempList = u.get('dishList') # dishList = [{'dishName': '1', 'createTime':''}]
                    ttList = []
                    for v in tempList:
                        v['diningNo'] = diningNo
                        v['diningName'] = diningName
                        v['stallNo'] = stallNo
                        v['stallName'] = stallName
                        v['createTime'] = globalTimeToString(v.get('createTime'))
                        v['updateTime'] = globalTimeToString(v.get('updateTime'))
                        imageUrl = ''
                        imageId = v.get('imageId')
                        if imageId is not None and len(imageId) > 10:
                            imageUrl = f'/api/dish/v1/query_Img/{imageId}'
                        v['imageUrl'] = imageUrl
                        ttList.append(v)
                    dishList.extend(ttList)
            elif len(stallNos) <= 0: # 只根据diningNo字段查询, 即查询该用户关联的所有餐厅所有档口的菜品
                if u.get('diningNo') in diningNos:
                    diningNo = u.get('diningNo')
                    stallNo = u.get('stallNo')
                    diningName, stallName = queryDiningNameStallName(diningNo, stallNo)
                    tempList = u.get('dishList') # dishList = [{'dishName': '1', 'createTime':''}]
                    ttList = []
                    for v in tempList:
                        v['diningNo'] = diningNo
                        v['diningName'] = diningName
                        v['stallNo'] = stallNo
                        v['stallName'] = stallName
                        v['createTime'] = globalTimeToString(v.get('createTime'))
                        v['updateTime'] = globalTimeToString(v.get('updateTime'))
                        imageUrl = ''
                        imageId = v.get('imageId')
                        if imageId is not None and len(imageId) > 10:
                            imageUrl = f'/api/dish/v1/query_Img/{imageId}'
                        v['imageUrl'] = imageUrl
                        ttList.append(v)
                    dishList.extend(ttList)
            else: # 当stallNo=["档口Id1", "档口Id2", ...]时，只根据stallNo查询，即查询档口组合
                if u.get('stallNo') in stallNos:
                    diningNo = u.get('diningNo')
                    stallNo = u.get('stallNo')
                    diningName, stallName = queryDiningNameStallName(diningNo, stallNo)
                    tempList = u.get('dishList')
                    ttList = []
                    for v in tempList:
                        v['diningNo'] = diningNo
                        v['diningName'] = diningName
                        v['stallNo'] = stallNo
                        v['stallName'] = stallName
                        v['createTime'] = globalTimeToString(v.get('createTime'))
                        v['updateTime'] = globalTimeToString(v.get('updateTime'))
                        imageUrl = ''
                        imageId = v.get('imageId')
                        if imageId is not None and len(imageId) > 10:
                            imageUrl = f'/api/dish/v1/query_Img/{imageId}'
                        v['imageUrl'] = imageUrl
                        ttList.append(v)
                    dishList.extend(ttList)

        dishList2 = []
        if dishState != 'all':
            for w in dishList:
                if w.get('dishState') == dishState:
                    dishList2.append(w)

            if len(dishList2) > 0:
                dishList = dishList2
            else:
                return totalPages, totalCount, []
        
        dishList3 = []
        if '全部' != meunName:
            for x in dishList:
                if x.get('menuNames') is not None:
                    if meunName in x.get('menuNames'):
                        dishList3.append(x)            
            dishList = dishList3           

        # reverse=False 升序
        dishList = sorted(dishList, key=operator.itemgetter('updateTime'), reverse=True)
        totalCount = int(len(dishList))
        totalPages = int((totalCount + pageSize) / pageSize)
        if len(dishList) == 0:
            totalPages = 0

        dishList_page = dishList[(startPage-1)*pageSize:(startPage-1)*pageSize+pageSize]

        return totalPages, totalCount, dishList_page
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryMenuDishes(diningNo, stallNo, menuName):
    '''
    查询档口指定餐次菜品信息
    '''
    try:       
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = mg_client[dbSynPosDishes][collectionDishList].find_one(cond)
        dishList = []
        # 如果不存在
        if res is None:
            return dishList

        for v in res.get('dishList'):
            menuNames = v.get('menuNames')
            # 如果传入的menuId存在于该条菜品记录中
            if menuName in menuNames:
                dish = {
                    'dishId': v.get('dishId'),
                    'dishName': v.get('dishName'),
                    'dishPrice': v.get('dishPrice'),
                    'dishUnit': v.get('dishUnit'),
                    'dishDesc': v.get('dishDesc'),
                    'dishSort': v.get('dishSort'),
                    'createTime': globalTimeToString(v.get('createTime')),
                    'updateTime': globalTimeToString(v.get('updateTime')),
                    'menuNames': v.get('menuNames'),
                    'classNames': v.get('classNames'),
                    'dishState': v.get('dishState'),
                    'checkFailDesc': v.get('checkFailDesc'),
                    'imageId': v.get('imageId')
                }
                dishList.append(dish)

        return dishList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryDishesFstImg(imageId):
    '''
    获取菜品封面图
    '''
    try:       
        mg_client = get_mongo_client()
        cond = {'imageId': imageId}
        res = mg_client[dbSynPosDishes][collectionImageList].find_one(cond)
        # 如果不存在
        if res is None:
            return None

        data = {
            'imageId': res.get('imageId'),
            'imageSrc': res.get('imageSrc'),
        }
        return data
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryDiningNameStallName(diningNo, stallNo):
    '''
    查询餐厅名和档口名
    '''
    try:
        diningName = ''
        stallName = ''
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosDining][collectionDiningList].find()
        for v in res:
            if v.get('diningNo') == diningNo:
               diningName = v.get('diningName')
            tempres = v.get('stallList')
            if tempres is not None:
                for r in tempres:
                    if r.get('stallNo') == stallNo:
                        stallName = r.get('stallName')

        return diningName, stallName
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def query_Img(imageId):
    '''
    查询图片
    '''
    try:
        bill_image_path = f'{image_path}/{imageId}.jpg'
        if os.path.exists(bill_image_path) is True:
            return send_from_directory(image_path, f'{imageId}.jpg', as_attachment=True)

        mg_client = get_mongo_client()
        cond = {'imageId': imageId}
        res = mg_client[dbSynPosDishes][collectionImageList].find_one(cond)
        # 如果不存在
        if res is None:
            return None

        imageSrc = res.get('imageSrc')
        if imageSrc is None or len(imageSrc) < 100:
            return None

        imgData = base64.b64decode(imageSrc)
        nparr = np.frombuffer(imgData, np.uint8)
        img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        cv2.imwrite(bill_image_path, img_np)

        return send_from_directory(image_path, f'{imageId}.jpg', as_attachment=True)
    except Exception as e:
        raise ErrMongoClient.data(str(e))
    
def queryIsHaveDishes(diningNo, stallNo):
    '''
    查询某档口下是否有菜
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = mg_client[dbSynPosDishes][collectionDishList].find_one(cond)
        if res is None:
            return None
        
        dishList = res.get('dishList')
        if dishList is not None and len(dishList) > 0:
            return True
        
        return False
    except Exception as e:
        raise ErrMongoClient.data(str(e))
    

def query_passed_class(diningNo, stallNo):
    try:       
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = mg_client[dbSynPosDishes][collectionDishList].find_one(cond)
        res_classList = []
        if res is None:
            return res_classList

        dishList = res.get('dishList')
        if dishList is None:
            return res_classList

        if len(dishList) <= 0: # 防止None崩溃
            return res_classList

        # 将dishList下的menuNames[]中的类别名去重存储
        # classNames = ["素菜", "肉菜"]
        classNames = []
        for v in dishList:
            # 该菜品没通过审核
            if v.get('dishState') != 'pass':
                continue
            cn = v.get('classNames')
            if cn is not None:
                for v1 in cn:
                    if v1 not in classNames:
                        classNames.append(v1)

        # dishList档口菜品表中的classList=[{"className": "主食", "classSort": 1},{}]
        classList = res.get('classList')
        if classList is None:
            for class_name in classNames:
                cls = {'className': class_name, 'classSort': 1}
                res_classList.append(cls)

            return res_classList

        for class_name in classNames:
            classSort = 1
            for v in classList:
                if v.get('className') == class_name:
                    classSort = v.get('classSort')
                    break
            if classSort is None:
                classSort = 1

            cls = {'className': class_name, 'classSort': classSort}
            res_classList.append(cls)

        # reverse=False 升序
        res_classList = sorted(res_classList, key=operator.itemgetter('classSort'), reverse=False)
        return res_classList
    except Exception as e:
        raise ErrMongoClient.data(str(e))